library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity MT9V032 is
  port(TW_Clk : in std_logic;
       TW_Data : inout std_logic);
end MT9V032;

architecture sim2 of MT9V032 is

  signal sData,sClk,dir : std_logic:='1';
  type states is (idle,address,reg,read1,read2,write1,write2,recAck,sendAck);
  signal cs : states:=idle;
  signal sysClk : std_logic:='0';
  signal systemClockTime : time :=26.6 ns;
  signal regAddress : std_logic_vector(15 downto 0);
  signal dataCounter : std_logic_vector(4 downto 0);
  signal myAddress : std_logic_vector(6 downto 0):="0011001";
  signal DataEdge : std_logic_vector(1 downto 0):="00";
  signal prevData,DataFallingEdge,DataRisingEdge : std_logic:='0';
begin
  
  sysClk <= not sysClk after systemClockTime/2;
  
  sClk<=TW_Clk;
  
  --Bi-Directional Ports  
  process (TW_Data,dir)
	begin
    if Dir = '1' then
      sData <= TW_Data;
    end if;
	end process;
	
	process (dir,sData)
	begin
	  if Dir = '0' then
	    TW_Data <= sData;
	  else
	    TW_Data <= 'Z';
	  end if;
  end process;
  
  ------------------------------
  -- Edge detector
  ------------------------------
  process(sData,sysClk)
  begin
    if rising_edge(sysClk) then
	   DataEdge<=DataEdge(0) & sData;
		
		if DataEdge = "00" and prevData = '1' then
		  DataFallingEdge <= '1';
		  DataRisingEdge<='0';
		  prevData<='0';
		elsif DataEdge = "11" and prevData = '0' then
		  prevData<='1';
		  DataFallingEdge<='0';
		  DataRisingEdge<='1';
		else
		  DataFallingEdge<='0';
		  DataRisingEdge<='0';
		end if;
	 end if;
  end process;
  
  --Control
  process(cs)
  begin
    if rising_edge(sysClk) then
      case cs is
        when idle =>
          if sClk = '1' and DataFallingEdge = '1' then
            cs <= address;
          end if;
        when address =>
          null;
        when reg =>
          null;
        when read1 =>
          null;
        when read2 =>
          null;
        when write1 =>
          null;
        when write2 =>
          null;
        when recAck =>
          null;
        when sendAck =>
          null;
      end case;
    end if;
  end process;
  
  --Datapath
  process(cs)
  begin
    if rising_edge(sysClk) then
      case cs is
        when idle =>
          null;
        when address =>
          null;
        when reg =>
          null;
        when read1 =>
          null;
        when read2 =>
          null;
        when write1 =>
          null;
        when write2 =>
          null;
        when recAck =>
          null;
        when sendAck =>
          null;
      end case;
    end if;
  end process;
  
end sim2;